package org.jeecg.modules.wmhb.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wmhb.util.WmhbUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 任务表
 * @Author: jeecg-boot
 * @Date: 2024-09-05
 * @Version: V1.0
 */
@Api(tags = "任务表")
@RestController
@RequestMapping("/wmhb/wmTask")
@Slf4j
public class WmTaskController extends JeecgController<WmTask, IWmTaskService> {
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmItemService wmItemService;
    @Autowired
    private IWmProductBomService wmProductBomService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;
    @Autowired
    private IWmPurchaseTaskbookBomService wmPurchaseTaskbookBomService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
	private IWmTaskBomService wmTaskBomService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IWmContractProductService wmContractProductService;
    @Autowired
    private IWmProductRecptService wmProductRecptService;
    @Autowired
    private IWmProductSaleService wmProductSaleService;
    @Autowired
    private IWmItemTypeService wmItemTypeService;
    @Autowired
    private IWmProjectStatisticService wmProjectStatisticService;
    @Autowired
    private IWmTaskbookFlowService wmTaskbookFlowService;
    @Autowired
    ISysBaseAPI sysBaseApi;
    @Autowired
    private IWmProductDebugService wmProductDebugService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IWmContractService wmContractService;
    @Autowired
    private IWmProjectService wmProjectService;

    /**
     * 留存任务列表
     *
     * @param wmContractId
     * @return
     */
    //@AutoLog(value = "任务-留存任务列表")
    @ApiOperation(value = "任务-留存任务列表", notes = "任务-留存任务列表")
    @GetMapping(value = "/remainList")
    public Result<List<WmDepartRemainTaskVo>> remainList(@RequestParam(name = "wmContractId", required = false) String wmContractId, @RequestParam(name = "wmContractProductId", required = false) String wmContractProductId, @RequestParam(name = "buId", required = false) String buId){
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmContractProductId)) {
            //获取选中的合同产品ID及其子产品ID列表
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmContractProductId);
        }
        else if(!StringUtils.isEmpty(wmContractId)) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = new ArrayList<>();
            wmContractIdList.add(wmContractId);
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        List<String> buDepartList = wmTaskbookFlowService.selectBuDepart(buId);
        List<WmDepartRemainTaskVo> wmDepartRemainTaskVoList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            wmDepartRemainTaskVoList = wmTaskService.remainList(buId, contractProductIdList, buDepartList);
        }
        return Result.OK(wmDepartRemainTaskVoList);
    }

    /**
     * 报料任务列表(管理员)
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-报料任务列表(管理员)")
    @ApiOperation(value = "任务-报料任务列表(管理员)", notes = "任务-报料任务列表(管理员)")
    @GetMapping(value = "/orderManagerList")
    public Result<IPage<WmTask>> queryManagerOrderList(WmTask wmTask,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        String statusOfParam = wmTask.getStatus();
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_ORDERED);
        statusList.add(UserConstant.TASK_STATUS_SKILL_CHANGE);
        statusList.add(UserConstant.TASK_STATUS_PRODUCED);
        statusList.add(UserConstant.TASK_STATUS_SALED);
        statusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
        statusList.add(UserConstant.TASK_STATUS_DEBUGING);
        statusList.add(UserConstant.TASK_STATUS_DEBUGED);
        statusList.add(UserConstant.TASK_STATUS_ARRIVED);
        statusList.add(UserConstant.TASK_STATUS_FINISHED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCING);
        statusList.add(UserConstant.TASK_STATUS_PURCHASED);
        statusList.add(UserConstant.TASK_STATUS_BOM_REACHED);

        wmTask.setStatus(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.in("status", statusList);//设计确认状态、已核减状态、技改状态才能报料，其他为已报料之后的状态
        queryWrapper.eq("is_start_point", UserConstant.SYS_YES);

        //机械生产任务书不需要设计者ID，电仪生产任务书需要设计师ID不为空
        queryWrapper.and(
                i -> i.eq("taskbook_type", UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC).isNotNull("design_user_id").ne("design_user_id","")
                      .or()
                      .eq("taskbook_type", UserConstant.TASKBOOK_TYPE_PRODUCE)
        );

        if(!StringUtils.isEmpty(statusOfParam)) {
            if (statusOfParam.equals(UserConstant.TASK_STATUS_ASSIGNED)) {
                //有仓库用户ID说明已分配
                queryWrapper.isNotNull("storage_user_id").ne("storage_user_id", "");
            } else if (statusOfParam.equals(UserConstant.TASK_STATUS_WAIT_ASSIGN)) {
                //没有仓库用户ID说明未分配
                queryWrapper.isNull("storage_user_id");
            }
        }

        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }

        queryWrapper.orderByDesc("create_time");
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);
        }

        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setWmTaskbook(wmTaskbook);
            wmTaskListFinal.add(wmTaskItem);
        }
        pageList.setRecords(wmTaskListFinal);
        return Result.OK(pageList);
    }

    /**
     * 报料任务列表
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-报料任务列表")
    @ApiOperation(value = "任务-报料任务列表", notes = "任务-报料任务列表")
    @GetMapping(value = "/orderList")
    public Result<IPage<WmTask>> queryOrderList(WmTask wmTask,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        String statusOfParam = wmTask.getStatus();
        List<String> statusList = new ArrayList<>();
        wmTask.setStatus(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("is_start_point", UserConstant.SYS_YES);
        //机械生产任务书不需要设计者ID，电仪生产任务书需要设计师ID不为空
        queryWrapper.and(
                i -> i.eq("taskbook_type", UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC).isNotNull("design_user_id").ne("design_user_id","")
                        .or()
                        .eq("taskbook_type", UserConstant.TASKBOOK_TYPE_PRODUCE)
        );

        //非管理员和没有角色须是指派人员
        Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
        if(roles.isEmpty() || !roles.contains("admin")) {
            queryWrapper.eq("storage_user_id", sysUser.getId());
        }
        if(StringUtils.isEmpty(statusOfParam)) {
            statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
            statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
            statusList.add(UserConstant.TASK_STATUS_ORDERED);
            statusList.add(UserConstant.TASK_STATUS_SKILL_CHANGE);
            statusList.add(UserConstant.TASK_STATUS_PRODUCED);
            statusList.add(UserConstant.TASK_STATUS_SALED);
            statusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
            statusList.add(UserConstant.TASK_STATUS_DEBUGING);
            statusList.add(UserConstant.TASK_STATUS_DEBUGED);
            statusList.add(UserConstant.TASK_STATUS_ARRIVED);
            statusList.add(UserConstant.TASK_STATUS_FINISHED);
            statusList.add(UserConstant.TASK_STATUS_PRODUCING);
            statusList.add(UserConstant.TASK_STATUS_PURCHASED);
            statusList.add(UserConstant.TASK_STATUS_BOM_REACHED);
        }
        else{
            //已报料
            if(statusOfParam.equals(UserConstant.TASK_STATUS_ORDERED)){
                statusList.add(UserConstant.TASK_STATUS_ORDERED);
                statusList.add(UserConstant.TASK_STATUS_SKILL_CHANGE);
                statusList.add(UserConstant.TASK_STATUS_PRODUCED);
                statusList.add(UserConstant.TASK_STATUS_SALED);
                statusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
                statusList.add(UserConstant.TASK_STATUS_DEBUGING);
                statusList.add(UserConstant.TASK_STATUS_DEBUGED);
                statusList.add(UserConstant.TASK_STATUS_ARRIVED);
                statusList.add(UserConstant.TASK_STATUS_FINISHED);
                statusList.add(UserConstant.TASK_STATUS_PRODUCING);
                statusList.add(UserConstant.TASK_STATUS_PURCHASED);
                statusList.add(UserConstant.TASK_STATUS_BOM_REACHED);
            }
            else{
                //未报料（电仪生产任务未设计审核通过，机械生产任务为生产审核通过）
                statusOfParam = statusOfParam + "," + UserConstant.TASK_STATUS_PRODUCE_APPROVED;
                statusList = Arrays.asList(statusOfParam.split(","));
            }
        }
        queryWrapper.in("status", statusList);//设计确认状态、已核减状态、技改状态才能报料，其他为已报料之后的状态

        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }

        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);
        }

        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setWmTaskbook(wmTaskbook);
            wmTaskListFinal.add(wmTaskItem);
        }
        pageList.setRecords(wmTaskListFinal);
        return Result.OK(pageList);
    }

    /**
     * 设计任务列表（设计和采购用）
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-设计任务列表")
    @ApiOperation(value = "任务-设计任务列表", notes = "任务-设计任务列表")
    @GetMapping(value = "/designList")
    public Result<IPage<WmTask>> queryDesignList(WmTask wmTask,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            //获取选中的合同产品ID及其子产品ID列表
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        String statusOfParam = wmTask.getStatus();
        wmTask.setStatus(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"

        //1、查询设计任务的任务书ID列表(先查出所有的设计任务ID及其祖先任务ID，再查询属于上一步任务ID列表中的根任务列表，最后查询属于第一步任务ID列表中的根任务的子任务)
        List<WmTask> wmTaskList = wmTaskService.selectTaskIdOfDesignList(wmTask.getTaskbookType(), statusOfParam, contractProductIdList);

        //2、查询条件查询的任务ID以及父辈ID列表
        List<String> taskIdListQuery = new ArrayList<>();//起点设计任务及其父辈ID列表
        for(WmTask wmTaskQuery: wmTaskList){
            //起点设计任务ID列表
            taskIdListQuery.add(wmTaskQuery.getId());

            //父辈任务ID列表
            List<String> ancestorIdList = Arrays.asList(wmTaskQuery.getAncestors().split(","));
            for(String id: ancestorIdList){
                if(!id.equals("0")){
                    taskIdListQuery.add(id);
                }
            }
        }

        //3、查询任务书下面的根任务列表（分页）
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO);
        if(!taskIdListQuery.isEmpty()) {
            queryWrapper.in("id", taskIdListQuery);
        }
        else{
            queryWrapper.eq("id", "empty");//数据为空
        }
        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }
        queryWrapper.orderByDesc("create_time");

        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);//设计起点任务列表的wmContractProductId为空，不能通过此条件查询，其祖先任务才有此wmContractProductId值
        }

        //4、通过祖先节点和查询条件查询出的任务ID列表获取子任务
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setTaskbookStatus(wmTaskbook.getStatus());
            List<WmTask> wmTaskListChildren = wmTaskService.selectTaskChildrenInIdList(wmTaskItem, taskIdListQuery);
            wmTaskItem.setChildren(wmTaskListChildren);
            wmTaskItem.setKey(wmTaskItem.getId());
            wmTaskItem.setParentId(wmTaskItem.getPid());
            wmTaskItem.setTitle(wmTaskItem.getName());
            wmTaskItem.setIsLeaf(wmTaskListChildren.isEmpty());
            wmTaskItem.setWmTaskbook(wmTaskbook);
            if(StringUtils.isEmpty(wmTaskbook.getCurrentVersion()) || (wmTaskbook.getCurrentVersion().equals(wmTaskItem.getCurrentVersion()))) {
                wmTaskListFinal.add(wmTaskItem);
            }
        }
        pageList.setRecords(wmTaskListFinal);
        pageList.setTotal(wmTaskListFinal.size());

        return Result.OK(pageList);
    }

    /**
     * 工艺任务列表（设计和采购用）
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-工艺任务列表")
    @ApiOperation(value = "任务-工艺任务列表", notes = "任务-工艺任务列表")
    @GetMapping(value = "/processList")
    public Result<IPage<WmTask>> queryProcessList(WmTask wmTask,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            //获取选中的合同产品ID及其子产品ID列表
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        String statusOfParam = wmTask.getStatus();
        wmTask.setStatus(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"

        //1、查询工艺任务的任务书ID列表(先查出所有的工艺任务ID及其祖先任务ID，再查询属于上一步任务ID列表中的根任务列表，最后查询属于第一步任务ID列表中的根任务的子任务)
        List<WmTask> wmTaskList = wmTaskService.selectTaskOfProcessList(wmTask.getTaskbookType(), statusOfParam, contractProductIdList);

        //2、查询条件查询的任务ID以及父辈ID列表
        List<String> taskIdListQuery = new ArrayList<>();//起点工艺任务及其父辈ID列表
        for(WmTask wmTaskQuery: wmTaskList){
            //起点设计任务ID列表
            taskIdListQuery.add(wmTaskQuery.getId());

            //父辈任务ID列表
            List<String> ancestorIdList = Arrays.asList(wmTaskQuery.getAncestors().split(","));
            for(String id: ancestorIdList){
                if(!id.equals("0")){
                    taskIdListQuery.add(id);
                }
            }
        }

        //3、查询任务书下面的根任务列表（分页）
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO);
        if(!taskIdListQuery.isEmpty()) {
            queryWrapper.in("id", taskIdListQuery);
        }
        else{
            queryWrapper.eq("id", "empty");//数据为空
        }
        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }
        queryWrapper.orderByDesc("create_time");

        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);//设计起点任务列表的wmContractProductId为空，不能通过此条件查询，其祖先任务才有此wmContractProductId值
        }

        //4、通过祖先节点和查询条件查询出的任务ID列表获取子任务
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setTaskbookStatus(wmTaskbook.getStatus());
            List<WmTask> wmTaskListChildren = wmTaskService.selectTaskChildrenInIdList(wmTaskItem, taskIdListQuery);
            wmTaskItem.setChildren(wmTaskListChildren);
            wmTaskItem.setKey(wmTaskItem.getId());
            wmTaskItem.setParentId(wmTaskItem.getPid());
            wmTaskItem.setTitle(wmTaskItem.getName());
            wmTaskItem.setIsLeaf(wmTaskListChildren.isEmpty());
            wmTaskItem.setWmTaskbook(wmTaskbook);
            if(StringUtils.isEmpty(wmTaskbook.getCurrentVersion()) || (wmTaskbook.getCurrentVersion().equals(wmTaskItem.getCurrentVersion()))) {
                wmTaskListFinal.add(wmTaskItem);
            }
        }
        pageList.setRecords(wmTaskListFinal);
        pageList.setTotal(wmTaskListFinal.size());

        return Result.OK(pageList);
    }

    /**
     * 生产任务列表
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-生产任务列表")
    @ApiOperation(value = "任务-生产任务列表", notes = "任务-生产任务列表")
    @GetMapping(value = "/produceList")
    public Result<IPage<WmTask>> queryProduceList(WmTask wmTask,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

        wmTask.setPid(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO); //查询根生产任务
        queryWrapper.in("taskbook_type", produceTypeList);
        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }
        queryWrapper.orderByDesc("create_time");

        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);//设计起点任务列表的wmContractProductId为空，不能通过此条件查询
        }

        //查询子任务，直到有发货单位为止
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setTaskbookStatus(wmTaskbook.getStatus());
            wmTaskItem.setWmTaskbook(wmTaskbook);

            //查询ID属于taskIdListQuery里面的子任务
            List<WmTask> wmTaskListChildren = wmTaskService.selectTaskChildrenUntilSendUnit(wmTaskItem);
            wmTaskItem.setChildren(wmTaskListChildren);
            wmTaskItem.setKey(wmTaskItem.getId());
            wmTaskItem.setParentId(wmTaskItem.getPid());
            wmTaskItem.setTitle(wmTaskItem.getName());
            wmTaskItem.setIsLeaf(wmTaskListChildren.isEmpty());

            if(StringUtils.isEmpty(wmTaskbook.getCurrentVersion()) || (wmTaskbook.getCurrentVersion().equals(wmTaskItem.getCurrentVersion()))) {
                wmTaskListFinal.add(wmTaskItem);
            }
        }
        pageList.setRecords(wmTaskListFinal);
        pageList.setTotal(wmTaskListFinal.size());

        return Result.OK(pageList);
    }

    /**
     * 调试任务列表
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-调试任务列表")
    @ApiOperation(value = "任务-调试任务列表", notes = "任务-调试任务列表")
    @GetMapping(value = "/debugList")
    public Result<IPage<WmTask>> queryDebugList(WmTask wmTask,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"

        //1、查询调试任务的任务书ID列表(先查出所有的调试任务ID及其祖先任务ID，再查询属于上一步任务ID列表中的根任务列表，最后查询属于第一步任务ID列表中的根任务的子任务)
        List<WmTask> wmTaskList = wmTaskService.selectTaskOfDebugList(contractProductIdList);

        //2、查询条件查询的任务ID以及父辈ID列表
        List<String> taskIdListQuery = new ArrayList<>();//起点设计任务及其父辈ID列表
        for(WmTask wmTaskQuery: wmTaskList){
            //起点调试任务ID列表
            taskIdListQuery.add(wmTaskQuery.getId());

            //父辈任务ID列表
            List<String> ancestorIdList = Arrays.asList(wmTaskQuery.getAncestors().split(","));
            for(String id: ancestorIdList){
                if(!id.equals("0")){
                    taskIdListQuery.add(id);
                }
            }
        }

        //3、查询任务书下面的根任务列表（分页）
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO);
        if(!taskIdListQuery.isEmpty()) {
            queryWrapper.in("id", taskIdListQuery);
        }
        else{
            queryWrapper.eq("id", "empty");//数据为空
        }
        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }
        queryWrapper.orderByDesc("create_time");
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);
        }

        //4、通过祖先节点和查询条件查询出的任务ID列表获取子任务
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setTaskbookStatus(wmTaskbook.getStatus());
            List<WmTask> wmTaskListChildren = wmTaskService.selectTaskChildrenInIdList(wmTaskItem, taskIdListQuery);
            wmTaskItem.setChildren(wmTaskListChildren);
            wmTaskItem.setKey(wmTaskItem.getId());
            wmTaskItem.setParentId(wmTaskItem.getPid());
            wmTaskItem.setTitle(wmTaskItem.getName());
            wmTaskItem.setIsLeaf(wmTaskListChildren.isEmpty());
            wmTaskItem.setWmTaskbook(wmTaskbook);
            if(StringUtils.isEmpty(wmTaskbook.getCurrentVersion()) || (wmTaskbook.getCurrentVersion().equals(wmTaskItem.getCurrentVersion()))) {
                wmTaskListFinal.add(wmTaskItem);
            }
        }
        pageList.setRecords(wmTaskListFinal);
        pageList.setTotal(wmTaskListFinal.size());

        return Result.OK(pageList);
    }

    /**
     * 采购任务列表(仓库用)
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-采购任务列表")
    @ApiOperation(value = "任务-采购任务列表", notes = "任务-采购任务列表")
    @GetMapping(value = "/purchaseList")
    public Result<IPage<WmTask>> queryPurchaseList(WmTask wmTask,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        String statusOfParam = wmTask.getStatus();
        wmTask.setStatus(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO);
        queryWrapper.eq("taskbook_type", UserConstant.TASKBOOK_TYPE_PURCHASE);

        //非管理员和没有角色须是指派人员
        Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
        if(roles.isEmpty() || !roles.contains("admin")) {
            //queryWrapper.eq("storage_user_id", sysUser.getId());//仓库不指派了，所有仓库角色都能收到
        }
        if(!StringUtils.isEmpty(statusOfParam)) {
            List<String> statusList = new ArrayList<>();
            statusList.add(UserConstant.TASK_STATUS_ARRIVED);
            statusList.add(UserConstant.TASK_STATUS_FINISHED);
            if(statusOfParam.equals(UserConstant.TASK_STATUS_ARRIVED)){
                //已到货
                queryWrapper.in("status", statusList);
            }
            else{
                //未到货
                queryWrapper.notIn("status", statusList);
            }
        }

        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }

        queryWrapper.orderByDesc("create_time");
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);
        }

        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setWmTaskbook(wmTaskbook);
            wmTaskListFinal.add(wmTaskItem);
        }
        pageList.setRecords(wmTaskListFinal);
        return Result.OK(pageList);
    }

    /**
     * 工程任务列表
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-工程任务列表")
    @ApiOperation(value = "任务-工程任务列表", notes = "任务-工程任务列表")
    @GetMapping(value = "/engineerList")
    public Result<IPage<WmTask>> queryEngineerList(WmTask wmTask,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        IPage<WmTask> pageList = null;
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmTask.getWmContractProductId())) {
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTask.getWmContractProductId());
        }
        else if(req.getParameterMap().get("wmContractId").length > 0) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = Arrays.asList(req.getParameterMap().get("wmContractId"));
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        wmTask.setPid(null);
        wmTask.setWmContractProductId(null);                                     //清空wmContractProductId=某值的查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
        newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"

        //1、查询调试任务的任务书ID列表(先查出所有的调试任务ID及其祖先任务ID，再查询属于上一步任务ID列表中的根任务列表，最后查询属于第一步任务ID列表中的根任务的子任务)
        List<WmTask> wmTaskList = wmTaskService.selectTaskOfEngineerList(contractProductIdList);

        //2、查询条件查询的任务ID以及父辈ID列表
        List<String> taskIdListQuery = new ArrayList<>();//起点设计任务及其父辈ID列表
        for(WmTask wmTaskQuery: wmTaskList){
            //起点调试任务ID列表
            taskIdListQuery.add(wmTaskQuery.getId());

            //父辈任务ID列表
            List<String> ancestorIdList = Arrays.asList(wmTaskQuery.getAncestors().split(","));
            for(String id: ancestorIdList){
                if(!id.equals("0")){
                    taskIdListQuery.add(id);
                }
            }
        }

        //3、查询任务书下面的根任务列表（分页）
        Boolean flag = true;
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, newParameterMap);
        queryWrapper.eq("ancestors", UserConstant.ANCESTOR_ZERO);
        if(!taskIdListQuery.isEmpty()) {
            queryWrapper.in("id", taskIdListQuery);
        }
        else{
            queryWrapper.eq("id", "empty");//数据为空
        }
        if(!contractProductIdList.isEmpty()) {
            queryWrapper.in("wm_contract_product_id", contractProductIdList);
        }
        else{
            queryWrapper.eq("wm_contract_product_id", "empty");//数据为空
        }
        queryWrapper.orderByDesc("create_time");
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
        } else {
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            pageList = wmTaskService.page(page, queryWrapper);
        }

        //4、通过祖先节点和查询条件查询出的任务ID列表获取子任务
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        for(WmTask wmTaskItem: pageList.getRecords()){
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
            WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
            wmTaskbook.setWmContract(wmContract);
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            wmTaskbook.setWmProject(wmProject);
            wmTaskItem.setTaskbookStatus(wmTaskbook.getStatus());
            List<WmTask> wmTaskListChildren = wmTaskService.selectTaskChildrenInIdList(wmTaskItem, taskIdListQuery);
            wmTaskItem.setChildren(wmTaskListChildren);
            wmTaskItem.setKey(wmTaskItem.getId());
            wmTaskItem.setParentId(wmTaskItem.getPid());
            wmTaskItem.setTitle(wmTaskItem.getName());
            wmTaskItem.setIsLeaf(wmTaskListChildren.isEmpty());
            wmTaskItem.setWmTaskbook(wmTaskbook);
            if(StringUtils.isEmpty(wmTaskbook.getCurrentVersion()) || (wmTaskbook.getCurrentVersion().equals(wmTaskItem.getCurrentVersion()))) {
                wmTaskListFinal.add(wmTaskItem);
            }
        }
        pageList.setRecords(wmTaskListFinal);
        pageList.setTotal(wmTaskListFinal.size());

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param wmTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-分页列表查询")
    @ApiOperation(value = "任务-分页列表查询", notes = "任务-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<IPage<WmTask>> queryPageList(WmTask wmTask,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
            List<WmTask> list = wmTaskService.queryTreeListNoPage(queryWrapper);
            IPage<WmTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = wmTask.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            wmTask.setPid(null);
            QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<WmTask> page = new Page<WmTask>(pageNo, pageSize);
            IPage<WmTask> pageList = wmTaskService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 【vue3专用】加载节点的子数据
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmTaskService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     *
     * @param async
     * @param pcode
     * @return
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmTaskService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     *
     * @param ls
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = wmTaskService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    /**
     * 获取子数据
     *
     * @param wmTask
     * @param req
     * @return
     */
    //@AutoLog(value = "任务-获取子数据")
    @ApiOperation(value = "任务-获取子数据", notes = "任务-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<WmTask>> queryPageList(WmTask wmTask, HttpServletRequest req) {
        QueryWrapper<WmTask> queryWrapper = QueryGenerator.initQueryWrapper(wmTask, req.getParameterMap());
        List<WmTask> list = wmTaskService.list(queryWrapper);
        IPage<WmTask> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return 返回 IPage
     * @return
     */
    //@AutoLog(value = "任务-批量获取子数据")
    @ApiOperation(value = "任务-批量获取子数据", notes = "任务-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<WmTask> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<WmTask> list = wmTaskService.list(queryWrapper);
            IPage<WmTask> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param wmTask
     * @return
     */
    @AutoLog(value = "任务-添加")
    @ApiOperation(value = "任务-添加", notes = "任务-添加")
    @RequiresPermissions("wmhb:wm_task:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody WmTask wmTask) {
        if (StringUtils.isEmpty(wmTask.getPid())){
            return Result.error("父任务ID不能为空");
        }
        if (!StringUtils.isEmpty(wmTask.getCode()) && UserConstant.NOT_UNIQUE.equals(wmTaskService.checkItemCodeUnique(wmTask))) {
            return Result.error("任务" + wmTask.getCode() + "编码已存在");
        }
        if (!StringUtils.isEmpty(wmTask.getName()) && UserConstant.NOT_UNIQUE.equals(wmTaskService.checkItemNameUnique(wmTask))) {
            return Result.error("任务" + wmTask.getCode() + "名称已存在");
        }

        if(!StringUtils.isEmpty(wmTask.getWmTaskbookId())) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_FINISHED)){
                return Result.error("当前任务书状态不能新增任务");
            }
            wmTask.setCurrentNodeIndex(wmTaskbook.getCurrentNodeIndex());
            wmTask.setCurrentNodeId(wmTaskbook.getCurrentNodeId());
        }
        else{
            return Result.error("任务书ID不能为空");
        }

        WmTask taskParent = wmTaskService.getById(wmTask.getPid());     //物料产品父产品
        if(taskParent == null){
            return Result.error("根任务只能新建任务书时新建");
        }

        //1、创建产品及产品BOM（如果任务类型为自制，外协，外购）
        if(wmTask.getType().equals(UserConstant.TASK_TYPE_SELF) || wmTask.getType().equals(UserConstant.TASK_TYPE_OUT) || wmTask.getType().equals(UserConstant.TASK_TYPE_BUY)) {
            //更新任务BOM
            //WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookId(wmTask.getWmTaskbookId());
            //wmTaskBomService.updateTaskbom(wmTaskRoot, taskParent, wmTask, null);
        }

        //2、保存任务，前端传是否为起点任务值（报料任务单位）
        if(StringUtils.isEmpty(wmTask.getIsStartPoint()) || !wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            if (taskParent.getIsStartPoint().equals(UserConstant.SYS_YES)) {
                //如果父任务是起点任务，则新建的任务的报料任务ID为父任务ID
                wmTask.setOrderTaskId(taskParent.getId());
            }
            if (!StringUtils.isEmpty(taskParent.getOrderTaskId())) {
                //如果父任务的报料任务ID不为空，则新任务报料任务ID为父任务的报料任务ID
                wmTask.setOrderTaskId(taskParent.getOrderTaskId());
            }
        }
        wmTask.setBuId(taskParent.getBuId());
        wmTask.setTaskbookType(taskParent.getTaskbookType());
        wmTask.setWmContractProductId(taskParent.getWmContractProductId());
        if(wmTask.getPlanBeginTime() != null){
            wmTask.setPlanBeginTime(taskParent.getPlanBeginTime());
        }
        if(wmTask.getPlanEndTime() != null){
            wmTask.setPlanEndTime(taskParent.getPlanEndTime());
        }

        if(StringUtils.isEmpty(wmTask.getWeight())){
            wmTask.setWeight("1");
        }
        wmTaskService.addWmTask(wmTask);

        //3、保存任务流程
        if(!CollectionUtils.isEmpty(wmTask.getWmTaskFlowList())) {
            Integer index= 0;
            for (WmTaskFlow wmTaskFlow : wmTask.getWmTaskFlowList()) {
                wmTaskFlow.setWmTaskId(wmTask.getId());
                wmTaskFlow.setOrderNum(index);
                wmTaskFlowService.save(wmTaskFlow);
                index++;
            }
        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmTask
     * @return
     */
    @AutoLog(value = "任务-编辑")
    @ApiOperation(value = "任务-编辑", notes = "任务-编辑")
    @RequiresPermissions("wmhb:wm_task:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> edit(@RequestBody WmTask wmTask) {
        if (!StringUtils.isEmpty(wmTask.getCode()) && UserConstant.NOT_UNIQUE.equals(wmTaskService.checkItemCodeUnique(wmTask))) {
            return Result.error("任务" + wmTask.getCode() + "编码已存在");
        }
        if (!StringUtils.isEmpty(wmTask.getName()) && UserConstant.NOT_UNIQUE.equals(wmTaskService.checkItemNameUnique(wmTask))) {
            return Result.error("任务" + wmTask.getCode() + "名称已存在");
        }

        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PRODUCING);
        statusList.add(UserConstant.TASK_STATUS_PRODUCED);
        statusList.add(UserConstant.TASK_STATUS_SALED);
        statusList.add(UserConstant.TASK_STATUS_DEBUGED);
        statusList.add(UserConstant.TASK_STATUS_PURCHASED);
        statusList.add(UserConstant.TASK_STATUS_ARRIVED);
        statusList.add(UserConstant.TASK_STATUS_FINISHED);
        WmTask wmTaskOriginal = wmTaskService.getById(wmTask.getId());
        if(wmTaskOriginal != null && statusList.contains(wmTaskOriginal.getStatus())){
            //return Result.error("任务当前状态不能编辑");
        }

        //1、如果任务类型为安装自制，外协，外购，且编辑前后物料类型不一致
        if((wmTaskOriginal.getType().equals(UserConstant.TASK_TYPE_SELF) || wmTaskOriginal.getType().equals(UserConstant.TASK_TYPE_OUT) || wmTaskOriginal.getType().equals(UserConstant.TASK_TYPE_BUY)) && (!StringUtils.isEmpty(wmTask.getItemOrProduct()) && !wmTaskOriginal.getItemOrProduct().equals(wmTask.getItemOrProduct()))) {
            //更新任务BOM
            //WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookId(wmTaskOriginal.getWmTaskbookId());
            //WmTask wmTaskParent = wmTaskService.getById(wmTaskOriginal.getPid());
            //wmTaskBomService.updateTaskbom(wmTaskRoot, wmTaskParent, wmTask, wmTaskOriginal);
        }

        //2、任务及其子任务修改部门流程
        if(!CollectionUtils.isEmpty(wmTask.getWmTaskFlowList())) {
            List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
            for(WmTask wmTaskItem: wmTaskList) {
                //修改任务流程部门
                Integer index = 0;
                for (WmTaskFlow wmTaskFlow : wmTask.getWmTaskFlowList()) {
                    //计算需求时间
                    Integer needTime = 0;
                    if(wmTaskFlow.getFinishTime() != null){
                        //有设置截至完成时间
                        if(index == 0){
                            needTime = WmhbUtil.countDiffDay(wmTask.getPlanBeginTime(), wmTaskFlow.getFinishTime());
                        }
                        else{
                            needTime = WmhbUtil.countDiffDay(wmTask.getWmTaskFlowList().get(index-1).getFinishTime(), wmTaskFlow.getFinishTime());
                        }
                    }

                    //修改或插入流程部门时间
                    WmTaskFlow wmTaskFlowExist = wmTaskFlowService.getByTaskAndDepart(wmTaskItem.getId(), wmTaskFlow.getDepartId(), index);
                    if(wmTaskFlowExist != null){
                        wmTaskFlowExist.setFinishTime(wmTaskFlow.getFinishTime());
                        wmTaskFlowExist.setChargeBy(wmTaskFlow.getChargeBy());
                        wmTaskFlowExist.setResponsibility(wmTaskFlow.getResponsibility());
                        wmTaskFlowExist.setNeedTime(needTime);
                        wmTaskFlowService.updateById(wmTaskFlowExist);
                    }
                    else{
                        wmTaskFlow.setWmTaskId(wmTaskItem.getId());
                        wmTaskFlow.setOrderNum(index);
                        wmTaskFlow.setNeedTime(needTime);
                        wmTaskFlowService.save(wmTaskFlow);
                    }
                    index++;
                }
            }
        }

        if(StringUtils.isEmpty(wmTask.getWeight())){
            wmTask.setWeight("1");
        }

        //3、修改当前任务
        wmTaskService.updateWmTask(wmTask);

        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-通过id删除")
    @ApiOperation(value = "任务-通过id删除", notes = "任务-通过id删除")
    @RequiresPermissions("wmhb:wm_task:delete")
    @DeleteMapping(value = "/delete")
    @Transactional
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PREPARE);
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            return Result.error("当前状态任务不能删除");
        }

        if (wmTaskService.checkHasItem(id)) {
            return Result.error("任务下是否有子任务，请先删除任务");
        }

        //删除任务
        wmTaskService.deleteWmTask(id);

        return Result.OK("删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "任务-通过id查询")
    @ApiOperation(value = "任务-通过id查询", notes = "任务-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmTask> queryById(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        if (wmTask == null) {
            return Result.error("未找到对应数据");
        }

        //任务及其子任务
        wmTask = wmTaskService.selectTreeChildrenWithTask(wmTask);

        //任务流程节点
        List<WmTaskFlow> wmTaskFlowList = wmTaskFlowService.queryByTaskId(id);
        wmTask.setWmTaskFlowList(wmTaskFlowList);

        //任务日志列表
        List<WmTaskLog> wmTaskLogList = wmTaskLogService.queryByTaskId(id);
        wmTask.setWmTaskLogList(wmTaskLogList);
        return Result.OK(wmTask);
    }

    /**
     * 通过id查询需要展开的节点
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "任务-通过id查询需要展开的节点", notes = "任务-通过id查询需要展开的节点")
    @GetMapping(value = "/getExpandKeysById")
    public Result<List<String>> getExpandKeysById(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        if (wmTask == null) {
            return Result.error("未找到对应数据");
        }

        List<String> keyList = wmTaskService.getExpandKeys(wmTask);
        return Result.OK(keyList);
    }

    /**
     * 导入组件BOM_2（电气设计或工艺）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel2/{wmTaskId}", method = RequestMethod.POST)
    @RequiresPermissions("wmhb:wm_task:importExcel")
    @ApiOperation(value = "任务-导入组件BOM", notes = "任务-导入组件BOM")
    @Transactional
    public Result<?> importExcel2(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmTaskId") String wmTaskId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BOMNode> list = ExcelImportUtil.importExcel(file.getInputStream(), BOMNode.class, params);
                WmBomResultVo wmBomResultVo = uploadProductProcess(list, wmTaskId);
                return Result.ok(wmBomResultVo);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    private WmBomResultVo uploadProductProcess(List<BOMNode> list, String wmTaskId) {
        List<BOMNode> newList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        WmTask wmTaskParent = wmTaskService.getById(wmTaskId);

        //外购件不用导入BOM清单
        if(!wmTaskParent.getType().equals(UserConstant.TASK_TYPE_BUY)) {
            try {
                //A、修改父任务状态为已导入
                WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskParent.getWmTaskbookId());
                List<String> statusList = new ArrayList<>();
                statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED); //该状态为技术设计审核（任务书审核）通过后导入工艺清单
                statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);    //该状态为生产审核通过后导入设计清单（电仪制造部）
                statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);   //该状态为技术主管对设计审核不通过后重新导入设计清单
                statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);     //该状态为技术主管对设计审核通过后导入工艺清单
                statusList.add(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED);  //该状态为技术主管对工艺审核不通过后重新导入工艺清单
                if (!statusList.contains(wmTaskbook.getStatus())) {
                    throw new RuntimeException("当前任务状态不允许导入");
                }

                WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
                //如果根任务类型为安装调试，技术服务，安装材料
                if (wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_INSTALL_DEBUG) || wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_TECHNOLOGY_SERVICE) || wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_MATERIAL)) {
                    throw new RuntimeException("当前任务类型不允许导入");
                }

                wmTaskParent.setBatchNo(batchNo);
                wmTaskParent.setStatus(wmTaskbook.getStatus());
                if (wmTaskParent.getId().equals(wmTaskRoot.getId())) {
                    //根节点为设计起始任务（改版后）
                    wmTaskParent.setIsStartPoint(UserConstant.SYS_YES); //工艺设计起点任务（改版后）
                }
                wmTaskService.updateById(wmTaskParent);

                //B、循环处理上传的产品
                for (BOMNode bomNode : list) {
                    if (StringUtils.isEmpty(bomNode.getName())) {
                        bomNode.setStatus("物料名称缺失");
                        bomNode.setResult("fail");
                        newList.add(bomNode);
                        continue;
                    }

                    //1、初始化父产品和父任务
                    WmTask taskParent = null;
                    if (!StringUtils.isEmpty(bomNode.getPcode())) {
                        taskParent = wmTaskService.selectTaskByCodeAndTaskParent(bomNode.getPcode(), wmTaskRoot);  //父任务
                        if (taskParent == null) {
                            throw new RuntimeException("父任务不存在");
                        }
                    } else {
                        taskParent = wmTaskService.getById(wmTaskParent.getId());
                    }

                    //2、保存任务
                    taskParent.setCanEditFlow(UserConstant.SYS_NO);
                    taskParent.setEnableFlag(UserConstant.ENABLE_FLAG_NO);
                    taskParent.setOrderTaskId(wmTaskParent.getId());
                    taskParent.setBuId(wmTaskParent.getBuId());
                    taskParent.setTaskbookType(wmTaskParent.getTaskbookType());
                    taskParent.setStatus(wmTaskbook.getStatus());
                    taskParent.setFactBeginTime(new Date());
                    WmTask wmTaskNew = wmTaskService.importComponentBom(bomNode, taskParent);

                    //3、保存任务流程
                    List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
                    wmTaskFlowService.saveTaskFlow(wmFlowDeptList, wmTaskNew);

                    //4、创建任务BOM,不包含半成品和成品，只包含物料
                    if (bomNode.getItemOrProduct().equals(UserConstant.PRODUCT_ITEM) && wmTaskNew != null) {
                        wmTaskBomService.importComponentBom(bomNode, wmTaskRoot);
                    }

                    bomNode.setStatus("导入成功");
                    bomNode.setResult("success");
                    newList.add(bomNode);
                }

                wmTaskbook.setCurrentVersion(batchNo);
                wmTaskbookService.updateById(wmTaskbook);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        WmBomResultVo wmBomResultVo = new WmBomResultVo();
        wmBomResultVo.setBomNodeList(newList);
        wmBomResultVo.setBatchNo(batchNo);
        wmBomResultVo.setWmTaskId(wmTaskId);
        return wmBomResultVo;
    }

    /**
     * 导入组件BOM（电气设计或工艺）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel/{wmTaskId}", method = RequestMethod.POST)
    @RequiresPermissions("wmhb:wm_task:importExcel")
    @ApiOperation(value = "任务-导入组件BOM", notes = "任务-导入组件BOM")
    @Transactional
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmTaskId") String wmTaskId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        WmBomResultVo wmBomResultVo = new WmBomResultVo();
        WmTask wmTaskParent = wmTaskService.getById(wmTaskId);
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskParent.getWmTaskbookId());
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        wmTaskRoot.setCurrentVersion(batchNo);

        if(!wmTaskId.equals(wmTaskRoot.getId())){
            return Result.error("只能在根任务上导入！");
        }

        wmTaskService.updateById(wmTaskRoot);//设置当前任务的当前BOM版本号
        deleteByBatchNoBackend(wmTaskRoot, wmTaskParent);
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取上传文件对象
                MultipartFile file = entity.getValue();
                Workbook workbook = WorkbookFactory.create(file.getInputStream());

                // 遍历所有工作表
                Integer sheetNum = workbook.getNumberOfSheets();
                for (int i = 0; i < sheetNum; i++) {
                    Integer sheetIndex = i;
                    if (sheetIndex < sheetNum) {
                        Sheet sheet = workbook.getSheetAt(i);
                        String sheetName = sheet.getSheetName();

                        ImportParams params = new ImportParams();
                        params.setStartSheetIndex(sheetIndex);
                        params.setSheetNum(1);        //读取几个sheet页
                        params.setTitleRows(0);       //标题行数
                        params.setHeadRows(1);        //头部行数
                        if (sheetName.equals("材料汇总")) {
                            List<WmMaterialVo> dataList = ExcelImportUtil.importExcel(file.getInputStream(), WmMaterialVo.class, params);
                            wmTaskBomService.importMaterialBom(dataList, wmTaskRoot);//插入材料　任务BOM
                            wmItemService.importMaterialBom(dataList, wmTaskRoot);  //插入材料BOM版本主数据
                        }
                        else if (sheetName.equals("外购件汇总")) {
                            List<WmBuyVo> dataList = ExcelImportUtil.importExcel(file.getInputStream(), WmBuyVo.class, params);
                            wmTaskBomService.importBuyBom(dataList, wmTaskRoot);//插入外购件　任务BOM
                            wmItemService.importBuyBom(dataList, wmTaskRoot);   //插入外购件BOM版本主数据
                        }
                        else if (sheetName.equals("产品BOM")) {
                            List<BOMNode> dataList = ExcelImportUtil.importExcel(file.getInputStream(), BOMNode.class, params);
                            wmBomResultVo = uploadProductProcess2(dataList, wmTaskbook, wmTaskRoot, wmTaskParent);
                        }
                    }
                }

                workbook.close();
                file.getInputStream().close();

                return Result.ok(wmBomResultVo);
            }
        }catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.error("文件导入失败！");
    }

    private WmBomResultVo uploadProductProcess2(List<BOMNode> list, WmTaskbook wmTaskbook, WmTask wmTaskRoot, WmTask wmTaskParent) {
        List<BOMNode> newList = new ArrayList<>();
        String batchNo = wmTaskRoot.getCurrentVersion();

        //外购件不用导入BOM清单
        if(!wmTaskParent.getType().equals(UserConstant.TASK_TYPE_BUY)) {
            try {
                //A、修改父任务状态为已导入
                List<String> statusList = new ArrayList<>();
                statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED); //该状态为技术设计审核（任务书审核）通过后导入工艺清单
                statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);    //该状态为生产审核通过后导入设计清单（电仪制造部）
                statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);   //该状态为技术主管对设计审核不通过后重新导入设计清单
                statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);     //该状态为技术主管对设计审核通过后导入工艺清单
                statusList.add(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED);  //该状态为技术主管对工艺审核不通过后重新导入工艺清单
                if (!statusList.contains(wmTaskbook.getStatus())) {
                    throw new RuntimeException("当前任务状态不允许导入");
                }

                //如果根任务类型为安装调试，技术服务，安装材料
                if (wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_INSTALL_DEBUG) || wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_TECHNOLOGY_SERVICE) || wmTaskRoot.getType().equals(UserConstant.TASK_TYPE_MATERIAL)) {
                    throw new RuntimeException("当前任务类型不允许导入");
                }

                wmTaskParent.setBatchNo(batchNo);
                wmTaskParent.setStatus(wmTaskbook.getStatus());
                if (wmTaskParent.getId().equals(wmTaskRoot.getId())) {
                    //根节点为设计起始任务（改版后）
                    wmTaskParent.setIsStartPoint(UserConstant.SYS_YES); //工艺设计起点任务（改版后）
                }
                wmTaskParent.setCurrentVersion(batchNo);
                wmTaskService.updateById(wmTaskParent);

                //B、循环处理上传的产品
                for (BOMNode bomNode : list) {
                    if (StringUtils.isEmpty(bomNode.getName())) {
                        bomNode.setStatus("物料名称缺失");
                        bomNode.setResult("fail");
                        newList.add(bomNode);
                        continue;
                    }

                    //1、初始化父产品和父任务
                    WmTask taskParent = null;
                    if (!StringUtils.isEmpty(bomNode.getPcode())) {
                        taskParent = wmTaskService.selectTaskByCodeAndTaskParent(bomNode.getPcode(), wmTaskRoot);  //父任务
                        if (taskParent == null) {
                            throw new RuntimeException("父任务不存在");
                        }
                    } else {
                        taskParent = wmTaskService.getById(wmTaskParent.getId());
                    }

                    //2、保存任务
                    taskParent.setCanEditFlow(UserConstant.SYS_NO);
                    taskParent.setEnableFlag(UserConstant.ENABLE_FLAG_NO);
                    taskParent.setOrderTaskId(wmTaskParent.getId());
                    taskParent.setBuId(wmTaskParent.getBuId());
                    taskParent.setTaskbookType(wmTaskParent.getTaskbookType());
                    taskParent.setStatus(wmTaskbook.getStatus());
                    taskParent.setFactBeginTime(new Date());
                    taskParent.setBatchNo(batchNo);
                    taskParent.setCurrentVersion(batchNo);
                    WmTask wmTaskNew = wmTaskService.importComponentBom(bomNode, taskParent);

                    //3、保存任务流程
                    List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
                    wmTaskFlowService.saveTaskFlow(wmFlowDeptList, wmTaskNew);

                    bomNode.setStatus("导入成功");
                    bomNode.setResult("success");
                    newList.add(bomNode);
                }

                wmTaskbook.setCurrentVersion(batchNo);
                wmTaskbookService.updateById(wmTaskbook);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        WmBomResultVo wmBomResultVo = new WmBomResultVo();
        wmBomResultVo.setBomNodeList(newList);
        wmBomResultVo.setBatchNo(batchNo);
        wmBomResultVo.setWmTaskId(wmTaskParent.getId());
        return wmBomResultVo;
    }

    /**
     * 通过批次号批量删除 已废弃
     *
     * @param batchNo
     * @param wmTaskId
     * @return
     */
    @AutoLog(value = "任务-通过批次号批量删除")
    @ApiOperation(value = "任务-通过批次号批量删除", notes = "任务-通过批次号批量删除")
    @RequiresPermissions("wmhb:wm_task:deleteBatch")
    @DeleteMapping(value = "/deleteByBatchNo")
    @Transactional
    public Result<String> deleteByBatchNo(@RequestParam(name = "batchNo", required = true) String batchNo, @RequestParam(name = "wmTaskId", required = true) String wmTaskId) {
        return Result.OK("批量删除成功!");
    }

    private void deleteByBatchNoBackend(WmTask wmTaskRoot, WmTask wmTaskParent) {
        //1、修改父任务
        LambdaUpdateWrapper<WmTask> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.set(WmTask::getBatchNo, null)
                .set(WmTask::getHasChild, UserConstant.HAS_CHILD_NO)
                .eq(WmTask::getId, wmTaskParent.getId());
        wmTaskService.update(null, updateWrapper1);

        //2、删除任务的子孙任务
        LambdaQueryWrapper<WmTask> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(WmTask::getBatchNo, wmTaskParent.getBatchNo());//此时父任务批次号已设置为空，不会受影响
        this.wmTaskService.remove(queryWrapper2);

        //3、删除任务BOM
        LambdaQueryWrapper<WmTaskBom> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(WmTaskBom::getWmTaskId, wmTaskRoot.getId());//此时父任务批次号已设置为空，不会受影响
        this.wmTaskBomService.remove(queryWrapper3);
    }

    //判断设计起点任务是否都已审批，则更新父任务和任务书的当前部门信息
    private void startPointTaskCheck(WmTask wmTask){
        Boolean flag = true;
        List<WmTask> wmTaskList = wmTaskService.startPointTask(wmTask.getWmTaskbookId());
        for(WmTask wmTaskItem: wmTaskList){
            //判断同级任务是否都大于当前任务的当前部门序号
            if(wmTaskItem.getCurrentNodeIndex() < wmTask.getCurrentNodeIndex()){
                flag = false;
            }

            if(wmTaskItem.getId().equals(wmTask.getId())){
                //获取最新的当前任务
                wmTask = wmTaskItem;
            }
        }

        if(flag){
            //更新祖先任务当前部门信息
            List<WmTask> ancestorTaskList = wmTaskService.ancestorTask(wmTask);
            if(!ancestorTaskList.isEmpty()) {
                for(WmTask wmTaskItem: ancestorTaskList) {
                    wmTaskItem.setCurrentNodeId(wmTask.getCurrentNodeId());
                    wmTaskItem.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
                    wmTaskItem.setCurrentNodeTime(new Date());
                    wmTaskItem.setProgress(wmTask.getProgress());
                    wmTaskItem.setStatus(wmTask.getStatus());
                    wmTaskService.updateById(wmTaskItem);
                }
            }

            //更新任务书当前部门信息
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setCurrentNodeId(wmTask.getCurrentNodeId());
            wmTaskbook.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 导入采购BOM
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importPurchaseBom/{wmTaskId}", method = RequestMethod.POST)
    @RequiresPermissions("wmhb:wm_task:importPurchaseBom")
    @ApiOperation(value = "任务-导入采购BOM", notes = "任务-导入采购BOM")
    @Transactional
    public Result<?> importPurchaseBom(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmTaskId") String wmTaskId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<PurchaseBom> list = ExcelImportUtil.importExcel(file.getInputStream(), PurchaseBom.class, params);
                WmPurchaseBomResultVo wmPurchaseBomResultVo = uploadPurchaseBomProcess(list, wmTaskId);
                return Result.ok(wmPurchaseBomResultVo);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    private WmPurchaseBomResultVo uploadPurchaseBomProcess(List<PurchaseBom> list, String wmTaskId) {
        List<PurchaseBom> newList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        try {
            //A、修改父任务状态为已导入
            WmTask wmTaskParent = wmTaskService.getById(wmTaskId);
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskParent.getWmTaskbookId());
            List<String> statusList = new ArrayList<>();
            statusList.add(UserConstant.TASK_STATUS_PREPARE);
            statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
            statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
            statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
            if (!statusList.contains(wmTaskbook.getStatus())) {
                throw new RuntimeException("当前任务状态不允许导入");
            }
            wmTaskParent.setBatchNo(batchNo);
            wmTaskService.updateById(wmTaskParent);

            //更新任务日志
            if(wmTaskParent.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE) || wmTaskParent.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)){
                wmTaskLogService.updateTaskLog(wmTaskParent.getId(), UserConstant.TASK_LOG_TYPE_PROCESS);
            }

            //B、循环处理上传的产品
            for (PurchaseBom bomNode : list) {
                if (StringUtils.isEmpty(bomNode.getName())) {
                    bomNode.setStatus("物料名称缺失");
                    bomNode.setResult("fail");
                    newList.add(bomNode);
                    continue;
                }

                //新增或修改采购BOM（通过名称和任务号判断是否已存在）
                List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.isBomExist(bomNode, wmTaskParent);
                if(wmPurchaseTaskbookBomList.isEmpty()) {
                    wmPurchaseTaskbookBomService.importWmPurchaseTaskbookBom(bomNode, wmTaskParent);
                }
                else{
                    //更新编码信息
                    if (!StringUtils.isEmpty(bomNode.getCode())) {
                        wmPurchaseTaskbookBomService.updateWmPurchaseTaskbookBom(bomNode, wmTaskParent);
                    }
                    else{
                        bomNode.setStatus("物料编码缺失");
                        bomNode.setResult("fail");
                        newList.add(bomNode);
                        continue;
                    }
                }
                bomNode.setStatus("导入成功");
                bomNode.setResult("success");
                newList.add(bomNode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        WmPurchaseBomResultVo wmPurchaseBomResultVo = new WmPurchaseBomResultVo();
        wmPurchaseBomResultVo.setBomNodeList(newList);
        wmPurchaseBomResultVo.setBatchNo(batchNo);
        wmPurchaseBomResultVo.setWmTaskId(wmTaskId);
        return wmPurchaseBomResultVo;
    }

    /**
     * 删除采购BOM
     *
     * @param batchNo
     * @param wmTaskId
     * @return
     */
    @AutoLog(value = "任务-删除采购BOM")
    @ApiOperation(value = "任务-删除采购BOM", notes = "任务-删除采购BOM")
    @RequiresPermissions("wmhb:wm_task:deletePurchaseBom")
    @DeleteMapping(value = "/deletePurchaseBom")
    @Transactional
    public Result<String> deletePurchaseBom(@RequestParam(name = "batchNo", required = true) String batchNo, @RequestParam(name = "wmTaskId", required = true) String wmTaskId) {
        //删除采购BOM
        LambdaQueryWrapper<WmPurchaseTaskbookBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmPurchaseTaskbookBom::getWmTaskId, wmTaskId);//此时父任务批次号已设置为空，不会受影响
        this.wmPurchaseTaskbookBomService.remove(queryWrapper);
        return Result.OK("批量删除成功!");
    }

    /**
     * 组件设计确认（或者技术服务报料设计提交）
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-组件设计确认")
    @ApiOperation(value = "任务-组件设计确认", notes = "任务-组件设计确认")
    @RequiresPermissions("wmhb:wm_task:confirm")
    @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doConfirm(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PREPARE);
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
        if (!statusList.contains(wmTask.getStatus())) {
            throw new RuntimeException("当前状态不能确认");
        }

        //任务书
        String nextStatus = "";
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_TECHNOLOGY)){
            //如果是技术服务任务书，设计确认后直接进入待调试
            nextStatus = UserConstant.TASK_STATUS_WAIT_DEBUG;
        }
        else{
            //电仪制造部电气设计审核完成时（下一步是仓库报料）
            nextStatus = UserConstant.TASK_STATUS_DESIGN_APPROVED;
        }

        if(!wmTask.getStatus().equals(nextStatus)) {
            //如果当前任务是根任务，更新任务书状态
            if (wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                wmTaskbook.setStatus(nextStatus);
                wmTaskbook.setProgress("30");//已审核算30%
                wmTaskbookService.updateById(wmTaskbook);
            }

            //获取所有子任务(包括自己)
            List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);

            //生产任务书类型
            List<String> produceTypeList = new ArrayList<>();
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);
            if(produceTypeList.contains(wmTaskbook.getTaskbookType()) && wmTaskList.size() <= 1){
                throw new RuntimeException("请上传设计清单");
            }

            for (WmTask wmTaskItem : wmTaskList) {
                wmTaskItem.setStatus(nextStatus); //更新任务的状态为已审核
                wmTaskItem.setProgress("30");//已审核算30%
                //任务进入下一个流程
                nextFlowTask(wmTaskItem);

                //判断同级的任务是否都已确认，有则更新父任务和任务书的当前部门信息
                if(wmTaskItem.getId().equals(wmTask.getId())) {
                    sameLevelTaskCheck(wmTaskItem);
                }
            }
        }

        //更新任务日志
        wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_DESIGN);
        return Result.OK("操作成功");
    }

    //如果同级别的任务都大于当前任务的当前部门序号，则更新父任务和任务书的当前部门信息
    private void sameLevelTaskCheck(WmTask wmTask){
        Boolean flag = true;
        List<WmTask> wmTaskList = wmTaskService.sameLevelTask(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            //判断同级任务是否都大于当前任务的当前部门序号
            if(wmTaskItem.getCurrentNodeIndex() < wmTask.getCurrentNodeIndex()){
                flag = false;
            }

            if(wmTaskItem.getId().equals(wmTask.getId())){
                //获取最新的当前任务
                wmTask = wmTaskItem;
            }
        }

        if(flag){
            //更新祖先任务当前部门信息
            List<WmTask> ancestorTaskList = wmTaskService.ancestorTask(wmTask);
            if(!ancestorTaskList.isEmpty()) {
                for(WmTask wmTaskItem: ancestorTaskList) {
                    wmTaskItem.setCurrentNodeId(wmTask.getCurrentNodeId());
                    wmTaskItem.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
                    wmTaskItem.setCurrentNodeTime(new Date());
                    wmTaskItem.setProgress(wmTask.getProgress());
                    wmTaskItem.setStatus(wmTask.getStatus());
                    wmTaskService.updateById(wmTaskItem);
                }
            }

            //更新任务书当前部门信息
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setCurrentNodeId(wmTask.getCurrentNodeId());
            wmTaskbook.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 领料生产
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-领料生产")
    @ApiOperation(value = "任务-领料生产", notes = "任务-领料生产")
    @RequiresPermissions("wmhb:wm_task:consume")
    @RequestMapping(value = "/consume", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doConsume(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_ORDERED);
        statusList.add(UserConstant.TASK_STATUS_PURCHASED);
        statusList.add(UserConstant.TASK_STATUS_BOM_REACHED);
        if (!statusList.contains(wmTask.getStatus())) {
            throw new RuntimeException("当前状态不能领料");
        }

        List<WmTask> wmTaskList = wmTaskService.selectChildTaskList(wmTask);
        wmTaskList.add(wmTask);

        //任务确认之后进入下一个流程
        for(WmTask wmTaskChild: wmTaskList){
            wmTaskChild.setStatus(UserConstant.TASK_STATUS_PRODUCING); //更新任务的状态为生产中
            wmTaskChild.setProgress("50");//领料生产算50%
            nextFlowTask(wmTaskChild);//更新任务到下一流程

            //判断同级的任务是否都已领料，有则更新父任务和任务书的当前部门信息
            if(wmTaskChild.getId().equals(wmTask.getId())) {
                sameLevelTaskCheck(wmTaskChild);
            }
        }

        //领料消费
        wmTaskBomService.consumeBom(id);

        //更新任务日志
        wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_CONSUME);
        return Result.OK("操作成功");
    }

    /**
     * 采购任务书采购下单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-采购下单")
    @ApiOperation(value = "任务-采购下单", notes = "任务-采购下单")
    @RequiresPermissions("wmhb:wm_task:purchase")
    @RequestMapping(value = "/purchase", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doPurchase(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_WAIT_PURCHASE);
        if (!statusList.contains(wmTask.getStatus())) {
            throw new RuntimeException("当前状态不能采购");
        }

        //任务书
        String nextStatus= UserConstant.TASK_STATUS_PURCHASED;
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());

        //如果当前任务是根任务，更新任务书状态
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setStatus(nextStatus);
            wmTaskbookService.updateById(wmTaskbook);
        }

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList) {
            wmTaskItem.setStatus(nextStatus); //更新任务的状态为已采购
            wmTaskItem.setProgress("70");//已采购算70%

            //任务进入下一个流程
            nextFlowTask(wmTaskItem);
        }
        return Result.OK("操作成功");
    }

    /**
     * 任务下一流程
     * @param wmTask
     * @return
     */
    private void nextFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、下一流程
        Integer nextIndex = wmTask.getCurrentNodeIndex() + 1;
        if(nextIndex >= wmFlowDeptList.size()){
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_TECHNOLOGY)){
                //技术服务任务书设计提交后没有下一流程（技术服务设计和调试是一个部门）
                wmTaskService.updateById(wmTask);
                return;
            }
            else{
                throw new RuntimeException("请补充完整的流程定义");
            }
        }

        //3、设置上一流程实际结束时间和当前流程实际开始时间
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex - 1);
        WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex);
        wmTaskFlowCurr.setFactEndTime(new Date());
        wmTaskFlowNext.setFactBeginTime(new Date());
        wmTaskFlowService.updateById(wmTaskFlowCurr);
        wmTaskFlowService.updateById(wmTaskFlowNext);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTask.setCurrentNodeIndex(nextIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setCurrentNodeIndex(nextIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 任务上一流程
     * @param wmTask
     * @return
     */
    private void prevFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、上一流程
        Integer prevIndex = wmTask.getCurrentNodeIndex() - 1;
        if(prevIndex < 0){
            throw new RuntimeException("流程异常");
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex);
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex + 1);
        wmTaskFlowPrev.setFactEndTime(null);
        wmTaskFlowCurr.setFactBeginTime(null);
        wmTaskFlowService.updateById(wmTaskFlowPrev);
        wmTaskFlowService.updateById(wmTaskFlowCurr);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTask.setCurrentNodeIndex(prevIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setCurrentNodeIndex(prevIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 查询任务的BOM清单及进度
     * @param wmTaskId
     * @return
     */
    @ApiOperation(value = "任务-查询任务的BOM清单及进度", notes = "任务-查询任务的BOM清单及进度")
    @GetMapping(value = "/selectTaskBomList")
    public Result<List<WmBomProgressVo>> selectTaskBomList(@RequestParam(name = "wmTaskId", required = true) String wmTaskId){
        WmTask wmTask = wmTaskService.getById(wmTaskId);

        //1、查询所有子任务（不包括自己）
        List<WmTask> childTaskList = wmTaskService.selectChildTaskList(wmTask);
        //2、加上自己
        childTaskList.add(wmTask);
        List<String> taskIdList = new ArrayList<>();//所有报料任务ID
        for(WmTask wmTaskItem: childTaskList){
            if(!StringUtils.isEmpty(wmTaskItem.getOrderTaskId()) && !taskIdList.contains(wmTaskItem.getOrderTaskId())){
                taskIdList.add(wmTaskItem.getOrderTaskId());
            }

            //根节点任务没有OrderTaskId，将根节点任务ID加入（其实改版后所有的报料任务ID都是根节点任务ID，此处代码没有简化）
            if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO) && !taskIdList.contains(wmTaskItem.getId())){
                taskIdList.add(wmTaskItem.getId());
            }
        }

        //3、查询所有到货BOM列表
        List<WmTaskBom> wmTaskBomList = new ArrayList<>();
        if(!taskIdList.isEmpty()) {
            wmTaskBomList = wmTaskBomService.listByWmTaskIds(taskIdList);
        }

        //4、到货BOM详情
        List<WmBomProgressVo> wmBomProgressVoList = copyToWmBomProgressVo(wmTask, wmTaskBomList);
        return Result.OK(wmBomProgressVoList);
    }

    /**
     * 转换任务BOM为BOM进度视图
     * @param wmTask
     * @param wmTaskBomList
     * @return
     */
    private List<WmBomProgressVo> copyToWmBomProgressVo(WmTask wmTask, List<WmTaskBom> wmTaskBomList){
        //核减后如果采购数量是0，则采购进度为100%
        List<String> noPurchaseStatus = new ArrayList<>();
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PREPARE);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PROCESS_SUBMITED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PROCESS_APPROVED);
        noPurchaseStatus.add(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED);

        List<WmBomProgressVo> wmBomProgressVoList = new ArrayList<>();
        for(WmTaskBom wmTaskBom: wmTaskBomList){
            if(StringUtils.isEmpty(wmTaskBom.getCode())){
                //没有金蝶编码的跳过
                continue;
            }

            BigDecimal progress = new BigDecimal(0);
            WmBomProgressVo wmBomProgressVo = new WmBomProgressVo();
            wmBomProgressVo.setId(wmTaskBom.getId());
            wmBomProgressVo.setName(wmTaskBom.getName());
            wmBomProgressVo.setCode(wmTaskBom.getCode());
            wmBomProgressVo.setSpecification(wmTaskBom.getSpecification());
            wmBomProgressVo.setSeriesNo(wmTaskBom.getSeriesNo());
            wmBomProgressVo.setProcessNo(wmTaskBom.getProcessNo());
            String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTaskBom.getUnitOfMeasure());
            wmBomProgressVo.setUnitOfMeasure(dictText);
            wmBomProgressVo.setNeedNum(wmTaskBom.getNeedNum());
            wmBomProgressVo.setPurchaseNum(wmTaskBom.getPurchaseNum());
            wmBomProgressVo.setArriveNum(wmTaskBom.getArriveNum());
            wmBomProgressVo.setWasteNum(wmTaskBom.getWasteNum());
            wmBomProgressVo.setReturnNum(wmTaskBom.getReturnNum());
            if(wmTaskBom.getOrderTime() != null){
                wmBomProgressVo.setOrder_time(WmhbUtil.convertDateToDatetime(wmTaskBom.getOrderTime()));
            }
            if(wmTaskBom.getPurchaseTime() != null) {
                wmBomProgressVo.setPurchase_time(WmhbUtil.convertDateToDatestring(wmTaskBom.getPurchaseTime()));
            }
            if(wmTaskBom.getArriveTime() != null) {
                wmBomProgressVo.setArrive_time(WmhbUtil.convertDateToDatestring(wmTaskBom.getArriveTime()));
            }
            if(wmTaskBom.getConsumeTime() != null) {
                wmBomProgressVo.setConsume_time(WmhbUtil.convertDateToDatetime(wmTaskBom.getConsumeTime()));
            }

            if(wmTaskBom.getCode().equals(UserConstant.JD_CODE_OF_INSTALL)){
                progress = new BigDecimal(100);
                wmBomProgressVo.setPurchase_time("安装服务没有跟踪");
                wmBomProgressVo.setArrive_time("安装服务没有跟踪");
            }
            else if((!StringUtils.isEmpty(wmTaskBom.getMingCheng()) && wmTaskBom.getMingCheng().contains("配套")) || (!StringUtils.isEmpty(wmTaskBom.getSpecification()) && wmTaskBom.getSpecification().contains("配套"))){
                progress = new BigDecimal(100);
                wmBomProgressVo.setPurchase_time("配套产品");
                wmBomProgressVo.setArrive_time("配套产品");
            }
            else if(wmTaskBom.getPurchaseNum() != null && wmTaskBom.getPurchaseNum() > 0){
                BigDecimal a = new BigDecimal(wmTaskBom.getArriveNum());
                BigDecimal b = new BigDecimal(Math.min(wmTaskBom.getPurchaseNum(), wmTaskBom.getNeedNum()));
                if(b.compareTo(BigDecimal.ZERO) != 0){
                    progress = a.multiply(new BigDecimal(100)).divide(b, 0, RoundingMode.HALF_UP);
                }
            }
            else if(!wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)
                    && !wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)
                    && wmTaskBom.getPurchaseNum() == 0
                    && !noPurchaseStatus.contains(wmTask.getStatus())
            ){
                progress = new BigDecimal(100);
                wmBomProgressVo.setPurchase_time("有库存，无需采购");
                wmBomProgressVo.setArrive_time("有库存，无需采购");
            }

            wmBomProgressVo.setProgress(progress);
            wmBomProgressVoList.add(wmBomProgressVo);
        }

        return bubbleSort(wmBomProgressVoList);
    }

    /**
     * 列表冒泡排序
     * @param wmBomProgressVoList
     * @return
     */
    private List<WmBomProgressVo> bubbleSort(List<WmBomProgressVo> wmBomProgressVoList){
        if(wmBomProgressVoList.isEmpty()){
            return wmBomProgressVoList;
        }

        for (int i = 0; i < wmBomProgressVoList.size() - 1; i++) {
            for (int j = 0; j < wmBomProgressVoList.size() - i - 1; j++) {
                if (wmBomProgressVoList.get(j).getProgress().compareTo(wmBomProgressVoList.get(j + 1).getProgress()) > 0) {//a>b
                    Collections.swap(wmBomProgressVoList, j, j + 1);
                }
            }
        }

        return wmBomProgressVoList;
    }

    /**
     * 获取产品BOM清单
     * @param wmItemId
     */
    @ApiOperation(value = "任务-获取产品BOM清单", notes = "任务-获取产品BOM清单")
    @GetMapping(value = "/previewItemBom")
    public Result<List<BOMNode>> previewItemBom(@RequestParam(name = "wmItemId", required = true) String wmItemId){
        WmItem wmItem = wmItemService.getById(wmItemId);
        List<BOMNode> bomNodeList = queryBomByWmItemId(wmItemId);
        //自己转换为BOMNode
        BOMNode bomNode = new BOMNode();
        bomNode.setCode(wmItem.getCode());
        bomNode.setName(wmItem.getName());
        bomNode.setItemOrProduct(wmItem.getItemOrProduct());
        bomNode.setQuantity(1D);
        bomNode.setPcode(null);//无法设置该属性
        bomNode.setSpecification(wmItem.getSpecification());
        bomNode.setUnitOfMeasure(wmItem.getUnitOfMeasure());
        bomNodeList.add(0, bomNode);

        return Result.OK(bomNodeList);
    }

    private List<BOMNode> queryBomByWmItemId(String wmItemId){
        List<BOMNode> bomNodeList  = new ArrayList<>();
        List<WmProductBom> wmProductBomList = wmProductBomService.queryChildrenByWmItemId(wmItemId);
        for(WmProductBom wmProductBom: wmProductBomList){
            WmItem wmItemParent = wmItemService.getById(wmProductBom.getWmItemId());
            BOMNode bomNode = new BOMNode();
            bomNode.setCode(wmProductBom.getBomItemCode());
            bomNode.setName(wmProductBom.getBomItemName());
            bomNode.setItemOrProduct(wmProductBom.getItemOrProduct());
            bomNode.setQuantity(wmProductBom.getQuantity());
            bomNode.setPcode(wmItemParent.getCode());
            bomNode.setSpecification(wmProductBom.getBomItemSpec());
            bomNode.setUnitOfMeasure(wmProductBom.getUnitOfMeasure());
            bomNodeList.add(bomNode);
            if(wmProductBom.getItemOrProduct().equals(UserConstant.PRODUCT_PRODUCT)){
                List<BOMNode> wmBomListChildren = queryBomByWmItemId(wmProductBom.getBomItemId());
                bomNodeList.addAll(wmBomListChildren);
            }
        }

        return bomNodeList;
    }

    /**
     * 导入技改BOM
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importSkillChangeExcel/{wmTaskId}", method = RequestMethod.POST)
    @RequiresPermissions("wmhb:wm_task:importSkillChangeExcel")
    @ApiOperation(value = "任务-导入技改BOM", notes = "任务-导入技改BOM")
    @Transactional
    public Result<?> importSkillChangeExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmTaskId") String wmTaskId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String nextVersion = format.format(new Date());
        WmBomResultVo wmBomResultVo = new WmBomResultVo();

        //获取父任务 任务书 上一个版本的根任务  流程部门列表
        WmTask wmTaskParent = wmTaskService.getById(wmTaskId);//当前导入的父任务
        if(!UserConstant.ANCESTOR_ZERO.equals(wmTaskParent.getAncestors())){
            return Result.error("只能在根任务上导入！");
        }
        if(!UserConstant.TASK_STATUS_DESIGN_APPROVED_OF_SKILL.equals(wmTaskParent.getStatus())){
            return Result.error("只有设计审批通过状态才能导入！");
        }
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskParent.getWmTaskbookId());
        WmTask rootTaskOfLastVersion = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskParent.getWmTaskbookId(), wmTaskbook.getCurrentVersion());

        //复制根任务为下一个版本的根任务
        WmTask rootTaskOfNextVersion = new WmTask();
        BeanUtils.copyProperties(rootTaskOfLastVersion, rootTaskOfNextVersion);
        rootTaskOfNextVersion.setCurrentVersion(nextVersion);
        rootTaskOfNextVersion.setId(null);
        wmTaskService.save(rootTaskOfNextVersion);
        WmItem wmItem = new WmItem();

        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取上传文件对象
                MultipartFile file = entity.getValue();
                Workbook workbook = WorkbookFactory.create(file.getInputStream());

                // 遍历所有工作表
                Integer sheetNum = workbook.getNumberOfSheets();
                for (int i = 0; i < sheetNum; i++) {
                    Integer sheetIndex = i;
                    if (sheetIndex < sheetNum) {
                        Sheet sheet = workbook.getSheetAt(i);
                        String sheetName = sheet.getSheetName();

                        ImportParams params = new ImportParams();
                        params.setStartSheetIndex(sheetIndex);
                        params.setSheetNum(1);        //读取几个sheet页
                        params.setTitleRows(0);       //标题行数
                        params.setHeadRows(1);        //头部行数
                        if (sheetName.equals("材料汇总")) {
                            //上一版本材料任务BOM列表
                            List<WmTaskBom> lastVersionTaskBomList = wmTaskBomService.queryByTaskAndVersion(rootTaskOfLastVersion, UserConstant.ITEM_TYPE_MATERIAL);
                            //递增的材料列表
                            List<WmMaterialVo> dataList = ExcelImportUtil.importExcel(file.getInputStream(), WmMaterialVo.class, params);
                            //根据新增的材料和上一个版本的物料材料清单，计算得出下一个版本的物料材料清单
                            List<WmMaterialVo> dataListNextVersion = getMaterialListOfSkill(dataList, lastVersionTaskBomList);
                            //插入新材料　任务BOM
                            wmTaskBomService.importMaterialBom(dataListNextVersion, rootTaskOfNextVersion);
                            //插入材料BOM版本主数据产品
                            wmItem = wmItemService.importMaterialBom(dataListNextVersion, rootTaskOfNextVersion);
                        }
                        else if (sheetName.equals("外购件汇总")) {
                            //上一版本外购件任务BOM列表
                            List<WmTaskBom> lastVersionTaskBomList = wmTaskBomService.queryByTaskAndVersion(rootTaskOfLastVersion, UserConstant.ITEM_TYPE_BUY);
                            //递增的外购件列表
                            List<WmBuyVo> dataList = ExcelImportUtil.importExcel(file.getInputStream(), WmBuyVo.class, params);
                            //根据新增的外购件和上一个版本的物料外购件清单，计算得出下一个版本的物料外购件清单
                            List<WmBuyVo> dataListNextVersion = getBuyListOfSkill(dataList, lastVersionTaskBomList);
                            //插入外购件　任务BOM
                            wmTaskBomService.importBuyBom(dataListNextVersion, rootTaskOfNextVersion);
                            //插入外购件BOM版本主数据
                            wmItem = wmItemService.importBuyBom(dataListNextVersion, rootTaskOfNextVersion);
                        }
                        else if (sheetName.equals("产品BOM")) {
                            List<BOMNode> dataList = ExcelImportUtil.importExcel(file.getInputStream(), BOMNode.class, params);
                            wmBomResultVo = uploadSkillChange(dataList, wmTaskbook, rootTaskOfNextVersion);
                        }
                    }
                }

                workbook.close();
                file.getInputStream().close();

                //设置当前任务的当前BOM版本号
                if(!StringUtils.isEmpty(wmItem.getId())) {
                    rootTaskOfNextVersion.setWmItemId(wmItem.getId());
                    wmTaskService.updateById(rootTaskOfNextVersion);
                }
                wmTaskbook.setCurrentVersion(nextVersion);
                wmTaskbookService.updateById(wmTaskbook);

                return Result.ok(wmBomResultVo);
            }
        }catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 技改后下一个版本的材料清单列表
     * @param wmMaterialVoList
     * @param lastVersionTaskBomList
     * @return
     */
    private List<WmMaterialVo> getMaterialListOfSkill(List<WmMaterialVo> wmMaterialVoList,  List<WmTaskBom> lastVersionTaskBomList){
        List<WmMaterialVo> dataListNextVersion = new ArrayList<>();
        //新导入物料数据为递增数据
        for(WmMaterialVo wmMaterialVo: wmMaterialVoList){
            Boolean flag = false;
            for(WmTaskBom wmTaskBom: lastVersionTaskBomList) {
                //如果相同编码并且相同型号的物料已经存在，则计算下一版本的BOM数量
                if (!StringUtils.isEmpty(wmTaskBom.getCode()) && wmTaskBom.getCode().equals(wmMaterialVo.getCode()) && !StringUtils.isEmpty(wmTaskBom.getSpecification()) && wmTaskBom.getSpecification().equals(wmMaterialVo.getSpecification())) {
                    WmMaterialVo wmMaterialVoNew = new WmMaterialVo();
                    BeanUtils.copyProperties(wmTaskBom, wmMaterialVoNew);
                    wmMaterialVoNew.setTotalWeight(wmTaskBom.getNeedNum() + wmMaterialVo.getTotalWeight());//新数量
                    wmMaterialVoNew.setQuantity(wmTaskBom.getNeedNum() + wmMaterialVo.getTotalWeight());
                    dataListNextVersion.add(wmMaterialVoNew);
                    flag = true;
                    break;
                }
            }

            //材料为新增
            if(!flag){
                dataListNextVersion.add(wmMaterialVo);
            }
        }

        //保留原有没有变更的物料
        for(WmTaskBom wmTaskBom: lastVersionTaskBomList) {
            Boolean flag = false;
            for(WmMaterialVo wmMaterialVo: wmMaterialVoList){
                if (!StringUtils.isEmpty(wmTaskBom.getCode()) && wmTaskBom.getCode().equals(wmMaterialVo.getCode()) && !StringUtils.isEmpty(wmTaskBom.getSpecification()) && wmTaskBom.getSpecification().equals(wmMaterialVo.getSpecification())) {
                    flag = true;
                    break;
                }
            }

            if(!flag && !StringUtils.isEmpty(wmTaskBom.getCode())){
                WmMaterialVo wmMaterialVoNew = new WmMaterialVo();
                BeanUtils.copyProperties(wmTaskBom, wmMaterialVoNew);
                wmMaterialVoNew.setTotalWeight(wmTaskBom.getNeedNum());
                wmMaterialVoNew.setQuantity(wmTaskBom.getNeedNum());
                dataListNextVersion.add(wmMaterialVoNew);
            }
        }

        return dataListNextVersion;
    };

    /**
     * 技改后下一个版本的外购件清单列表
     * @param wmBuyVoList
     * @param lastVersionTaskBomList
     * @return
     */
    private List<WmBuyVo> getBuyListOfSkill(List<WmBuyVo> wmBuyVoList, List<WmTaskBom> lastVersionTaskBomList){
        List<WmBuyVo> dataListNextVersion = new ArrayList<>();
        //新导入外购件数据为递增数据
        for(WmBuyVo wmBuyVo: wmBuyVoList){
            Boolean flag = false;
            for(WmTaskBom wmTaskBom: lastVersionTaskBomList) {
                //修改BOM数量
                if (!StringUtils.isEmpty(wmTaskBom.getCode()) && wmTaskBom.getCode().equals(wmBuyVo.getCode()) && !StringUtils.isEmpty(wmTaskBom.getSpecification()) && wmTaskBom.getSpecification().equals(wmBuyVo.getSpecification())) {
                    WmBuyVo wmBuyVoNew = new WmBuyVo();
                    BeanUtils.copyProperties(wmTaskBom, wmBuyVoNew);
                    wmBuyVoNew.setQuantity(wmTaskBom.getNeedNum() + wmBuyVo.getQuantity());
                    dataListNextVersion.add(wmBuyVoNew);
                    flag = true;
                    break;
                }
            }

            //外购件为新增
            if(!flag){
                dataListNextVersion.add(wmBuyVo);
            }
        }

        //保留原有没有变更的物料
        for(WmTaskBom wmTaskBom: lastVersionTaskBomList) {
            Boolean flag = false;
            for(WmBuyVo wmBuyVo: wmBuyVoList){
                if (!StringUtils.isEmpty(wmTaskBom.getCode()) && wmTaskBom.getCode().equals(wmBuyVo.getCode()) && !StringUtils.isEmpty(wmTaskBom.getSpecification()) && wmTaskBom.getSpecification().equals(wmBuyVo.getSpecification())) {
                    flag = true;
                    break;
                }
            }

            if(!flag && !StringUtils.isEmpty(wmTaskBom.getCode())){
                WmBuyVo wmBuyVoNew = new WmBuyVo();
                BeanUtils.copyProperties(wmTaskBom, wmBuyVoNew);
                wmBuyVoNew.setTotalWeight(wmTaskBom.getNeedNum());
                wmBuyVoNew.setQuantity(wmTaskBom.getNeedNum());
                dataListNextVersion.add(wmBuyVoNew);
            }
        }

        return dataListNextVersion;
    };

    private WmBomResultVo uploadSkillChange(List<BOMNode> list, WmTaskbook wmTaskbook, WmTask rootTaskOfNextVersion) {
        List<BOMNode> newList = new ArrayList<>();
        String nextVersion = rootTaskOfNextVersion.getCurrentVersion();
        //外购件不用导入BOM清单
        if(!rootTaskOfNextVersion.getType().equals(UserConstant.TASK_TYPE_BUY)) {
            try {
                List<String> statusList = new ArrayList<>();
                statusList.add(UserConstant.TASK_STATUS_FINISHED);
                statusList.add(UserConstant.TASK_STATUS_PROCESS_APPROVED);
                statusList.add(UserConstant.TASK_STATUS_SKILL_CHANGE);
                statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED_OF_SKILL);
                if (!statusList.contains(wmTaskbook.getStatus())) {
                    throw new RuntimeException("当前任务状态不允许技改");
                }

                //如果根任务类型不为设计任务书
                if (!rootTaskOfNextVersion.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)) {
                    throw new RuntimeException("当前任务类型不允许技改");
                }

                //新增根任务任务流程
                List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
                wmTaskFlowService.saveTaskFlow(wmFlowDeptList, rootTaskOfNextVersion);

                //循环处理上传的产品
                for (BOMNode bomNode : list) {
                    if (StringUtils.isEmpty(bomNode.getName())) {
                        bomNode.setStatus("物料名称缺失");
                        bomNode.setResult("fail");
                        newList.add(bomNode);
                        continue;
                    }

                    //1、初始化父产品和父任务
                    WmTask taskParent = null;
                    if (!StringUtils.isEmpty(bomNode.getPcode())) {
                        taskParent = wmTaskService.selectTaskByCodeAndTaskParent(bomNode.getPcode(), rootTaskOfNextVersion);  //父任务
                        if (taskParent == null) {
                            wmTaskService.removeById(rootTaskOfNextVersion.getId());
                            throw new RuntimeException("父任务不存在");
                        }
                    } else {
                        taskParent = rootTaskOfNextVersion;
                    }

                    //2、保存任务
                    taskParent.setCanEditFlow(UserConstant.SYS_NO);
                    taskParent.setEnableFlag(UserConstant.ENABLE_FLAG_NO);
                    taskParent.setOrderTaskId(rootTaskOfNextVersion.getId());
                    taskParent.setBuId(rootTaskOfNextVersion.getBuId());
                    taskParent.setTaskbookType(rootTaskOfNextVersion.getTaskbookType());
                    taskParent.setStatus(wmTaskbook.getStatus());
                    taskParent.setFactBeginTime(new Date());
                    taskParent.setBatchNo(nextVersion);
                    taskParent.setCurrentVersion(nextVersion);
                    WmTask wmTaskNew = wmTaskService.importComponentBom(bomNode, taskParent);

                    //3、保存子任务任务流程
                    wmTaskFlowService.saveTaskFlow(wmFlowDeptList, wmTaskNew);

                    bomNode.setStatus("导入成功");
                    bomNode.setResult("success");
                    newList.add(bomNode);
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        WmBomResultVo wmBomResultVo = new WmBomResultVo();
        wmBomResultVo.setBomNodeList(newList);
        wmBomResultVo.setBatchNo(nextVersion);
        wmBomResultVo.setWmTaskId(rootTaskOfNextVersion.getId());
        return wmBomResultVo;
    }

    /**
     * 任务（及其子任务）生产完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-生产完成")
    @ApiOperation(value = "任务-生产完成", notes = "任务（及其子任务）-生产完成")
    @RequiresPermissions("wmhb:wm_task:produceFinish")
    @Transactional
    @RequestMapping(value = "/produceFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> produceFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        List<String> statusList = new ArrayList<>();
        List<String> noProduceStatusList = new ArrayList<>();
        noProduceStatusList.add(UserConstant.TASK_STATUS_PRODUCED);
        noProduceStatusList.add(UserConstant.TASK_STATUS_SALED);
        noProduceStatusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
        noProduceStatusList.add(UserConstant.TASK_STATUS_DEBUGING);
        noProduceStatusList.add(UserConstant.TASK_STATUS_DEBUGED);
        noProduceStatusList.add(UserConstant.TASK_STATUS_ARRIVED);
        noProduceStatusList.add(UserConstant.TASK_STATUS_FINISHED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCING);
        statusList.addAll(noProduceStatusList);
        //获取事业部信息
        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId());

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            if(!statusList.contains(wmTaskItem.getStatus())){
                throw new RuntimeException("还有子任务未完成生产");
            }

            if(noProduceStatusList.contains(wmTaskItem.getStatus())){
                //已经报工过的跳过
                continue;
            }

            //新增报工记录
            WmProductRecpt wmProductRecpt = new WmProductRecpt();
            wmProductRecpt.setWmTaskId(wmTaskItem.getId());
            wmProductRecpt.setCompleteQuantity(wmTaskItem.getQuantity() - wmTaskItem.getCompleteNum());
            wmProductRecpt.setRemainQuantity(0D);
            wmProductRecpt.setBomRecptPercent("0");
            wmProductRecpt.setNotCompletePercent("0");

            if(wmTask.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
                wmProductRecpt.setWarehouseId(sysDepartModel.getProductWarehouseId());
            }
            else if(wmTask.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
                wmProductRecpt.setWarehouseId(sysDepartModel.getVendorWarehouseId());
            }
            else if(wmTask.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
                wmProductRecpt.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
            }
            wmProductRecptService.save(wmProductRecpt);

            wmTaskItem.setStatus(UserConstant.TASK_STATUS_PRODUCED); //更新任务的状态为生产完成
            wmTaskItem.setCompleteNum(wmTaskItem.getQuantity());
            wmTaskItem.setProgress("60");//生产完成算60%
            wmTaskService.updateById(wmTaskItem);
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress("60");//生产完成算完成60%
            wmTaskbookService.updateById(wmTaskbook);
        }

        //只有设计起点任务才更新报工日志
        if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_PRODUCE);
        }

        return Result.OK("操作成功");
    }

    /**
     * 任务（及其子任务）出库完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-出库完成")
    @ApiOperation(value = "任务-出库完成", notes = "任务（及其子任务）-出库完成")
    @RequiresPermissions("wmhb:wm_task:outFinish")
    @Transactional
    @RequestMapping(value = "/outFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> outFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId()); //获取事业部信息
        List<String> statusList = new ArrayList<>();
        List<String> noSaleStatusList = new ArrayList<>();
        noSaleStatusList.add(UserConstant.TASK_STATUS_SALED);
        noSaleStatusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
        noSaleStatusList.add(UserConstant.TASK_STATUS_DEBUGING);
        noSaleStatusList.add(UserConstant.TASK_STATUS_DEBUGED);
        noSaleStatusList.add(UserConstant.TASK_STATUS_ARRIVED);
        noSaleStatusList.add(UserConstant.TASK_STATUS_FINISHED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCED);
        statusList.addAll(noSaleStatusList);

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            if(!statusList.contains(wmTaskItem.getStatus())){
                throw new RuntimeException("还有子任务未完成生产");
            }

            if(noSaleStatusList.contains(wmTaskItem.getStatus())){
                //已经出库的跳过
                continue;
            }

            //新增出库记录
            WmProductSale wmProductSale = new WmProductSale();
            wmProductSale.setWmTaskId(wmTaskItem.getId());
            wmProductSale.setCompleteQuantity(wmTaskItem.getQuantity() - wmTaskItem.getSaleNum());
            wmProductSale.setRemainQuantity(0D);
            if(wmTask.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
                wmProductSale.setWarehouseId(sysDepartModel.getProductWarehouseId());
            }
            else if(wmTask.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
                wmProductSale.setWarehouseId(sysDepartModel.getVendorWarehouseId());
            }
            else if(wmTask.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
                wmProductSale.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
            }
            wmProductSaleService.save(wmProductSale);

            wmTaskItem.setStatus(UserConstant.TASK_STATUS_SALED); //更新任务的状态为出库完成
            wmTaskItem.setSaleNum(wmTaskItem.getQuantity());
            wmTaskItem.setProgress("70");//到货完成算70%
            wmTaskService.updateById(wmTaskItem);
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress("70");//出库完成算完成70%
            wmTaskbookService.updateById(wmTaskbook);
        }

        //只有设计起点任务才更新日志
        if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_SEND);
        }

        return Result.OK("操作成功");
    }

    /**
     * 任务（及其子任务）到货完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-到货完成")
    @ApiOperation(value = "任务-到货完成", notes = "任务（及其子任务）-到货完成")
    @RequiresPermissions("wmhb:wm_task:arriveFinish")
    @Transactional
    @RequestMapping(value = "/arriveFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> arriveFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        List<String> statusList = new ArrayList<>();
        List<String> noArriveStatusList = new ArrayList<>();
        noArriveStatusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
        noArriveStatusList.add(UserConstant.TASK_STATUS_DEBUGING);
        noArriveStatusList.add(UserConstant.TASK_STATUS_DEBUGED);
        noArriveStatusList.add(UserConstant.TASK_STATUS_ARRIVED);
        noArriveStatusList.add(UserConstant.TASK_STATUS_FINISHED);
        statusList.add(UserConstant.TASK_STATUS_SALED);
        statusList.addAll(noArriveStatusList);

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            if(!statusList.contains(wmTaskItem.getStatus())){
                throw new RuntimeException("还有子任务未完成出库");
            }

            if(noArriveStatusList.contains(wmTaskItem.getStatus())){
                //已经到货的跳过
                continue;
            }

            wmTaskItem.setStatus(UserConstant.TASK_STATUS_ARRIVED); //更新任务的状态为到货完成
            wmTaskItem.setArriveNum(wmTaskItem.getQuantity());
            wmTaskItem.setProgress("80");//到货完成算80%

            //出库记录状态为已到货
            wmProductSaleService.arriveByWmTaskId(wmTaskItem.getId());

            //任务进入下一个流程(生产和调试在一个大部门，不再区分小组和子部门)
            //nextFlowTask(wmTaskItem);

            //更新任务书当前流程部门
            if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                wmTaskbook.setProgress(wmTaskItem.getProgress());
                wmTaskbook.setStatus(wmTaskItem.getStatus());
                wmTaskbookService.updateById(wmTaskbook);
            }
        }

        //只有设计起点任务才更新日志
        if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_ARRIVE);
        }

        return Result.OK("操作成功");
    }

    /**
     * 任务（及其子任务）调试完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-调试完成")
    @ApiOperation(value = "任务-调试完成", notes = "任务（及其子任务）-调试完成")
    @RequiresPermissions("wmhb:wm_task:debugFinish")
    @Transactional
    @RequestMapping(value = "/debugFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> debugFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);
        List<String> statusList = new ArrayList<>();
        List<String> noDebugStatusList = new ArrayList<>();
        noDebugStatusList.add(UserConstant.TASK_STATUS_DEBUGED);
        noDebugStatusList.add(UserConstant.TASK_STATUS_FINISHED);
        statusList.add(UserConstant.TASK_STATUS_ARRIVED);
        statusList.addAll(noDebugStatusList);

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            //生产任务书类型
            List<String> produceTypeList = new ArrayList<>();
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);
            if(produceTypeList.contains(wmTaskItem.getTaskbookType()) && !statusList.contains(wmTaskItem.getStatus())){
                throw new RuntimeException("当前任务有未到货的子任务状态");
            }

            if(noDebugStatusList.contains(wmTaskItem.getStatus())){
                //已经调试的跳过
                continue;
            }

            wmTaskItem.setStatus(UserConstant.TASK_STATUS_DEBUGED); //更新任务的状态为调试完成
            wmTaskItem.setDebugNum(wmTaskItem.getQuantity());
            wmTaskItem.setProgress("90");//调试完成算90%
            wmTaskService.updateById(wmTaskItem);
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress("90");//调试完成算完成90%
            wmTaskbookService.updateById(wmTaskbook);
        }

        //新增调试记录
        WmProductDebug wmProductDebug = new WmProductDebug();
        wmProductDebug.setWmTaskId(id);
        wmProductDebug.setRemainQuantity(0D);
        wmProductDebug.setStatus(UserConstant.PRODUCT_DEBUG_STATUS_FINISHED);
        wmProductDebug.setCompleteQuantity(wmTask.getQuantity() - wmTask.getDebugNum());
        wmProductDebug.setProgress("100");
        wmProductDebugService.save(wmProductDebug);

        //只有设计起点任务才更新日志
        if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_DEBUG);
        }

        return Result.OK("操作成功");
    }

    /**
     * 任务（及其子任务）附加项完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-附加项完成")
    @ApiOperation(value = "任务-附加项完成", notes = "任务（及其子任务）-附加项完成")
    @RequiresPermissions("wmhb:wm_task:extraFinish")
    @Transactional
    @RequestMapping(value = "/extraFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> extraFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            wmTaskItem.setStatus(UserConstant.TASK_STATUS_EXTRA_CONFIRMED); //更新任务的状态为附加项全部完成
            wmTaskService.updateById(wmTaskItem);
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }

        return Result.OK("操作成功");
    }

    /**
     * 任务（及其子任务）完成
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务-任务完成")
    @ApiOperation(value = "任务-任务完成", notes = "任务（及其子任务）-任务完成")
    @RequiresPermissions("wmhb:wm_task:allFinish")
    @Transactional
    @RequestMapping(value = "/allFinish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> allFinish(@RequestParam(name = "id", required = true) String id) {
        WmTask wmTask = wmTaskService.getById(id);

        //1、所属任务书
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)){
            //设计任务书还未转换为生产任务书
            throw new RuntimeException("设计任务书还未转换为生产任务书");
        }
        if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)){
            //工艺任务书还未转换为生产任务书
            throw new RuntimeException("工艺任务书还未转换为生产任务书");
        }

        //2、任务书流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
        Integer lastIndex = wmFlowDeptList.size() - 1;
        WmFlowDept wmFlowDeptLast = wmFlowDeptList.get(lastIndex);//最后一个元素

        //获取所有子任务(包括自己)
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            if(wmTaskItem.getStatus().equals(UserConstant.TASK_STATUS_FINISHED)){
                //已经完成的跳过
                continue;
            }
            wmTaskItem.setStatus(UserConstant.TASK_STATUS_FINISHED); //更新任务的状态为完成
            wmTaskItem.setCurrentNodeId(wmFlowDeptLast.getDeptId());
            wmTaskItem.setCurrentNodeIndex(lastIndex);
            wmTaskItem.setSaleNum(wmTaskItem.getQuantity());
            wmTaskItem.setCompleteNum(wmTaskItem.getQuantity());
            wmTaskItem.setDebugNum(wmTaskItem.getQuantity());
            wmTaskItem.setProgress("100");
            if(wmTaskItem.getFactEndTime() == null) {
                wmTaskItem.setFactEndTime(new Date());
            }
            wmTaskService.updateById(wmTaskItem);
        }

        //更新任务的实际开始时间
        wmTaskFlowService.updateFactEndTimeByStep(wmTaskList, lastIndex);

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress("100");
            wmTaskbook.setFactBeginTime(new Date());
            wmTaskbookService.updateById(wmTaskbook);
        }

        //只有设计起点任务才更新日志
        if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_PLAN_FINISH);
        }

        return Result.OK("操作成功");
    }

    /**
     * 发货清单列表
     *
     * @param wmContractId
     * @param wmContractProductId
     * @return
     */
    //@AutoLog(value = "任务-发货清单列表")
    @ApiOperation(value = "任务-发货清单列表", notes = "任务-发货清单列表")
    @GetMapping(value = "/shouldSendList")
    public Result<List<WmTask>> shouldSendList(@RequestParam(name = "wmContractId", required = false) String wmContractId, @RequestParam(name = "wmContractProductId", required = false) String wmContractProductId, @RequestParam(name = "type", required = false) String type){
        List<String> contractProductIdList = new ArrayList<>();
        if(!StringUtils.isEmpty(wmContractProductId)) {
            //获取选中的合同产品ID及其子产品ID列表
            contractProductIdList = wmContractProductService.selectNodeAndChildren(wmContractProductId);
        }
        else if(!StringUtils.isEmpty(wmContractId)) {
            //查询合同ID下面的所有合同产品ID
            List<String> wmContractIdList = new ArrayList<>();
            wmContractIdList.add(wmContractId);
            contractProductIdList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
        }

        List<WmTask> wmTaskList = new ArrayList<>();
        if(type.equals(UserConstant.SEND_LIST_TYPE_SHOULD)) {
            //总应发清单
            wmTaskList = wmTaskService.shouldSendList(contractProductIdList);
        }
        else if(type.equals(UserConstant.SEND_LIST_TYPE_PRODUCE_PRODUCT)) {
            //成品（半成品）发货清单
            wmTaskList = wmTaskService.produceProduceSendList(contractProductIdList);
        }
        else if(type.equals(UserConstant.SEND_LIST_TYPE_PURCHASE_MATERIAL)) {
            //材料发货清单
            wmTaskList = wmTaskService.purchaseMaterialSendList(contractProductIdList);
        }
        else if(type.equals(UserConstant.SEND_LIST_TYPE_PURCHASE_PRODUCT)) {
            //外购件发货清单
            wmTaskList = wmTaskService.purchaseProductSendList(contractProductIdList);
        }
        else{
            //总应发清单
            wmTaskList = wmTaskService.shouldSendList(contractProductIdList);
        }
        return Result.OK(wmTaskList);
    }
}
